home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1130 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. Path: crl.crl.com!not-for-mail
  2. From: bobfry@crl.com (Robert Fry)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Help with gettng 2 chars into an integer!
  5. Date: 11 Jan 1996 08:32:30 -0800
  6. Organization: CRL Dialup Internet Access
  7. Message-ID: <4d3e2u$1hr@crl.crl.com>
  8. References: <4d2eh1$7pm@usc.edu>
  9. NNTP-Posting-Host: crl.com
  10.  
  11. wawda@scf.usc.edu (Abu Wawda) writes:
  12.  
  13. >Hi. I can't seem to figure out how to do this. Basically I have to chars that 
  14. >I want to put into a 2-byte integer. It seems easy at first, but I can't seem 
  15. >to figure out to do it with the bit-fidling operators (shifting or masking). 
  16. >Simple put, I'd like to do:
  17.  
  18. >    char a,b;
  19. >    int c;
  20.  
  21. >    a = 'A';
  22. >    b = 'B';
  23. >    c = ? /* the first byte in c should contain the value of a, and the 
  24. >second byte should contain the value of b */
  25.  
  26. Assuming chars are 8 bits, and assuming sizeof( int) >= 2 * sizeof( char),
  27. then you can use the following (note that it may be incorrect with 
  28. respect to the endianness of your CPU, and is clearly not portable):
  29.  
  30. c = (( a << 8) & 0x0FF00) | ( b & 0x00FF);
  31.  
  32. This will work. You can also put a and b into a union that contains an 
  33. array of 2 characters and an int. I'm not sure how to make the structure 
  34. independent of endianness, but someone should have an idea if that's an 
  35. issue for you.
  36.  
  37. I've used both, depending on the needs of the moment.
  38.  
  39.   Bob
  40.